<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号码" prop="carNo">
        <el-input
          v-model="queryParams.carNo"
          placeholder="请输入车牌号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:parkTicket:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:parkTicket:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:parkTicket:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		      :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:parkTicket:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:parkTicket:importData']"
        >批量添加月票</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="parkTicketList" border size="mini" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
      <el-table-column label="车牌号码" align="center" prop="carNo" width="100"/>
      <el-table-column label="月票费用(元)" align="center" prop="favorPrice" width="110"/>
      <el-table-column label="车主" align="center" prop="userName" width="130"/>
      <el-table-column label="车主电话" align="center" prop="userPhone" width="110"/>
      <el-table-column label="月票类型" align="center" prop="monthTicketConfigId" width="110" :formatter="ticketTypeFormat"/>
      <el-table-column label="停车场编号" align="center" prop="parkCodes" width="100"/>
      <el-table-column label="第三方系统订单号" align="center" prop="billCode" width="150"/>
      <el-table-column label="月票id" align="center" prop="monthTicketId" width="110"/>
      <el-table-column label="支付方式" align="center" prop="payMode" :formatter="payModeFormat"/>
<!--      <el-table-column label="支付方式备注" align="center" prop="payModeRemark" width="100"/>-->
      <el-table-column label="支付来源" align="center" prop="payOrigin" :formatter="payOriginFormat" width="100"/>
      <el-table-column label="备注" align="center" prop="payOriginRemark" />
      <el-table-column label="生效时间" align="center" prop="startTime" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createtime" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:parkTicket:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:parkTicket:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 车牌导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的车牌数据
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改月票管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"   label-width="120px">
        <el-form-item label="车牌号码" prop="carNo">
          <el-input v-model="form.carNo" placeholder="请输入车牌号码" />
        </el-form-item>
        <el-form-item label="车主姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入车主姓名" />
        </el-form-item>
        <el-form-item label="车主电话" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入车主电话" />
        </el-form-item>
        <el-form-item label="月票类型" prop="monthTicketConfigId">
          <el-select v-model="form.monthTicketConfigId" style="width: 100%"  placeholder="请选择月票类型" filterable clearable size="small">
            <el-option
              v-for="ticketType in parkTicketTypeOption"
              :key="ticketType.monthTicketConfigId"
              :label="ticketType.ticketName"
              :value="Number(ticketType.monthTicketConfigId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="datetime" style="width: 100%;"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择生效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间" prop="endTime">
          <el-date-picker clearable size="small"
                          v-model="form.endTime"
                          type="datetime" style="width: 100%;"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月票费用" prop="favorPrice">
          <el-input v-model="form.favorPrice" placeholder="请输入收取月票费用" />
        </el-form-item>
        <el-form-item label="备注" prop="payOriginRemark">
          <el-input v-model="form.payOriginRemark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listParkTicket, getParkTicket, delParkTicket, addParkTicket, updateParkTicket, exportParkTicket,importTemplate } from "@/api/system/parkTicket";
import { getAllList } from "@/api/system/parkTicketType";
import {getToken} from "@/utils/auth";

export default {
  name: "ParkTicket",
  components: {
  },
  data() {
    return {
	  //按钮loading
	  buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 月票管理表格数据
      parkTicketList: [],
      // 月票类型下拉列表
      parkTicketTypeOption: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 支付方式，参考附录字典
      payModeOptions: [],
      // 支付来源，参考附录字典
      payOriginOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNo: undefined,
      },
      // 车牌导入参数
      upload: {
        // 是否显示弹出层（车牌导入）
        open: false,
        // 弹出层标题（车牌导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的车牌数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/parkTicket/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carNo:[
          {required:true,message:"请输入车牌号",trigger:"blur"}
        ],
        userName:[
          {required:true,message:"请输入车主姓名",trigger:"blur"}
        ],
        userPhone:[
          {required:true,message:"请输入正确的电话号码",trigger:"blur",pattern: /^1[3456789]\d{9}$/}
        ],
        monthTicketConfigId:[
          {required:true,message:"请选择月票类型",trigger:"blur"}
        ],
        startTime:[
          {required:true,message:"请选择生效时间",trigger:"blur"}
        ],
        endTime:[
          {required:true,message:"请选择到期时间",trigger:"blur"}
        ],
        favorPrice:[
          {required:true,message:"价格不能为负数或小数点后只能有两位",trigger:"blur",pattern: /^(0|[1-9]\d{0,10})(\.\d{0,2})?$/}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAllList();
    this.getDicts("park_ticket_pay_mode").then(response => {
      this.payModeOptions = response.data;
    });
    this.getDicts("park_ticket_pay_origin").then(response => {
      this.payOriginOptions = response.data;
    });
  },
  methods: {
    /** 查询月票管理列表 */
    getList() {
      this.loading = true;
      listParkTicket(this.queryParams).then(response => {
        this.parkTicketList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllList(){
      let data={
        status:1
      }
      getAllList(data).then(response => {
        this.parkTicketTypeOption = response.data;
      });
    },
    // 支付方式，参考附录字典翻译
    payModeFormat(row, column) {
      return this.selectDictLabel(this.payModeOptions, row.payMode);
    },
    // 月票类型
    ticketTypeFormat(row, column) {
      for (let i = 0; i < this.parkTicketTypeOption.length; i++) {
        if (this.parkTicketTypeOption[i].monthTicketConfigId == row.monthTicketConfigId){
          return this.parkTicketTypeOption[i].ticketName;
        }
      }
    },
    // 支付来源，参考附录字典翻译
    payOriginFormat(row, column) {
      return this.selectDictLabel(this.payOriginOptions, row.payOrigin);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        monthTicketId: undefined,
        mqttCarId: undefined,
        uuid: undefined,
        userId: undefined,
        carNo: undefined,
        parkCodes: undefined,
        billCode: undefined,
        originPrice: undefined,
        favorPrice: undefined,
        payMode: undefined,
        payModeRemark: undefined,
        payOrigin: undefined,
        payOriginRemark: undefined,
        userName: undefined,
        userPhone: undefined,
        monthTicketConfigId: undefined,
        monthTicketBillId: undefined,
        remark: undefined,
        renewBy: undefined,
        renewTime: undefined,
        startTime: undefined,
        endTime: undefined,
        createtime: undefined,
        updatetime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导入模板下载操作 */
    handleDownload() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "批量添加月票";
      this.upload.open = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加月票管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getParkTicket(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改月票管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.compareTime(this.form.startTime,this.form.endTime) == false){
            this.msgError("请选择正确的时间段,失效时间不能小于生效时间!");
            this.buttonLoading = false;
            return false;
          }
          if (this.isVehicleNumber(this.form.carNo) == false){
            this.msgError("请填写正确的车牌号");
            this.buttonLoading = false;
            return false;
          }
          if (this.form.id != null) {
            updateParkTicket(this.form).then(response => {
              console.log(response)
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();

            });
          } else {
            addParkTicket(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除车牌号为"' + row.carNo + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delParkTicket(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有月票管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportParkTicket(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.queryParams.yearId = undefined;
      this.queryParams.gradeId = undefined;
      this.queryParams.classId = undefined;
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
